package org.blogwu.learn.multithread.chapter3.demo2;

import java.util.concurrent.locks.ReentrantLock;

public class Main2 {

    public static void main(String[] args) throws InterruptedException {
        DeadLock d1 = new DeadLock(1);
        DeadLock d2 = new DeadLock(2);
        d1.start();
        d2.start();
    }
}

class DeadLock extends Thread {
    static ReentrantLock reentrantLock1 = new ReentrantLock();
    static ReentrantLock reentrantLock2 = new ReentrantLock();
    int lock;

    public DeadLock(int lock) {
        this.lock = lock;
    }

    @Override
    public void run() {
        if (lock == 1) {
            while (true) {
                if (reentrantLock1.tryLock()) {
                    try {
                        try {
                            Thread.sleep(5000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        if (reentrantLock2.tryLock()) {
                            try {
                                System.out.println(Thread.currentThread().getName() + "doSthing() ok");
                                return;
                            } finally {
                                reentrantLock2.unlock();
                            }
                        }
                    } finally {
                        reentrantLock1.unlock();
                        System.out.println(Thread.currentThread().getName() + "  释放lock1");
                    }
                }
            }
        } else {
            while (true) {
                if (reentrantLock2.tryLock()) {
                    try {
                        try {
                            Thread.sleep(5000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }

                        if (reentrantLock1.tryLock()) {
                            try {
                                System.out.println(Thread.currentThread().getName() + "doSthing() ok");
                                return;
                            } finally {
                                reentrantLock1.unlock();
                            }
                        }
                    } finally {
                        reentrantLock2.unlock();
                        System.out.println(Thread.currentThread().getName() + "  释放lock2");
                    }
                }
            }
        }
    }
}
